//
//  NCChatViewController.m
//  AFNetworking
//
//  Created by LINAICAI on 2018/4/8.
//

#import "NCChatViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <MobileCoreServices/MobileCoreServices.h>

#import "WBTLAudioPlayer.h"
#import "NCChatViewSystemCell.h"

#import "NCChatViewLeftCell.h"
#import "NCChatViewRightCell.h"

#import "NCChatViewLeftPhotoCell.h"
#import "NCChatViewRightPhotoCell.h"

#import "NCChatViewLeftAudioCell.h"
#import "NCChatViewRightAudioCell.h"

#import "NCChatViewCustomCell.h"


#import "NCChatSystemMessage.h"
#import "NCChatTextMessage.h"
#import "NCChatAudioMessage.h"
#import "NCChatPhotoMessage.h"
#import "NCChatCustomMessage.h"

#import "NCRefreshNormalHeader.h"
#import "NCChatUserInfoManager.h"
#import "NCChatAudioTipsView.h"
static NSString *const leftCellID = @"NCChatViewLeftCell";
static NSString *const rightCellID = @"NCChatViewRightCell";

static NSString *const leftPhotoCellID = @"NCChatViewLeftPhotoCell";
static NSString *const rightPhotoCellID = @"NCChatViewRightPhotoCell";

static NSString *const leftAudioCellID = @"NCChatViewLeftAudioCell";
static NSString *const rightAudioCellID = @"NCChatViewRightAudioCell";

static NSString *const systemCellID = @"NCChatViewSystemCell";
static NSString *const customCellID = @"NCChatViewCustomCell";
@interface NCChatViewController ()<UITableViewDelegate,UITableViewDataSource,NCChatInputViewDelegate,NCChatInputViewDataSource,UIImagePickerControllerDelegate,UIScrollViewDelegate>

@property (nonatomic , strong)NSString *userId;
@end

@implementation NCChatViewController
#pragma mark- 懒加载
- (NCChatInputView *)chatInputView{
    if (!_chatInputView) {
        _chatInputView = [[NCChatInputView alloc]init];
        _chatInputView.dataSource = self;
        _chatInputView.delegate = self;
    }
    return _chatInputView;
}
- (UITableView *)chatTableView{
    if (!_chatTableView) {
        _chatTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _chatTableView.delegate = self;
        _chatTableView.dataSource = self;
        _chatTableView.tableFooterView = [UIView new];
        _chatTableView.showsVerticalScrollIndicator = NO;
        _chatTableView.showsHorizontalScrollIndicator = NO;
        
        _chatTableView.rowHeight = UITableViewAutomaticDimension;
        _chatTableView.estimatedSectionFooterHeight = 0;
        _chatTableView.estimatedSectionHeaderHeight = 0;
        _chatTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        //系统消息
        [_chatTableView registerNib:[UINib nibWithNibName:NSStringFromClass(NCChatViewSystemCell.class) bundle:[NSBundle bundleForClass:NCChatViewSystemCell.class]] forCellReuseIdentifier:systemCellID];
        //自定义消息
        [_chatTableView registerNib:[UINib nibWithNibName:NSStringFromClass(NCChatViewCustomCell.class) bundle:[NSBundle bundleForClass:NCChatViewCustomCell.class]] forCellReuseIdentifier:customCellID];
        //文本
        [_chatTableView registerNib:[UINib nibWithNibName:NSStringFromClass(NCChatViewLeftCell.class) bundle:[NSBundle bundleForClass:NCChatViewLeftCell.class]] forCellReuseIdentifier:leftCellID];
        [_chatTableView registerNib:[UINib nibWithNibName:NSStringFromClass(NCChatViewRightCell.class) bundle:[NSBundle bundleForClass:NCChatViewRightCell.class]] forCellReuseIdentifier:rightCellID];
        //图片
        [_chatTableView registerNib:[UINib nibWithNibName:NSStringFromClass(NCChatViewLeftPhotoCell.class) bundle:[NSBundle bundleForClass:NCChatViewLeftPhotoCell.class]] forCellReuseIdentifier:leftPhotoCellID];
        [_chatTableView registerNib:[UINib nibWithNibName:NSStringFromClass(NCChatViewRightPhotoCell.class) bundle:[NSBundle bundleForClass:NCChatViewRightPhotoCell.class]] forCellReuseIdentifier:rightPhotoCellID];
        //语音
        [_chatTableView registerNib:[UINib nibWithNibName:NSStringFromClass(NCChatViewLeftAudioCell.class) bundle:[NSBundle bundleForClass:NCChatViewLeftAudioCell.class]] forCellReuseIdentifier:leftAudioCellID];
        [_chatTableView registerNib:[UINib nibWithNibName:NSStringFromClass(NCChatViewRightAudioCell.class) bundle:[NSBundle bundleForClass:NCChatViewRightAudioCell.class]] forCellReuseIdentifier:rightAudioCellID];
        
        if (@available(iOS 11.0, *)) {
            [_chatTableView setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentAlways];
        } else {
            
        }

        
    }
    return _chatTableView;
}
#pragma mark- 重写
- (void)selectPictureWithType:(UIImagePickerControllerSourceType)type{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    picker.allowsEditing = NO;
    picker.sourceType = type;
    //相机类型（拍照、录像...）字符串需要做相应的类型转换
    picker.mediaTypes = @[(NSString *)kUTTypeImage];
    [self.navigationController presentViewController:picker animated:YES completion:nil];
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
- (BOOL)prefersStatusBarHidden{
    return NO;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
    return (toInterfaceOrientation == UIInterfaceOrientationPortrait);
}
- (BOOL)shouldAutorotate{
    return YES;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;//只支持这一个方向(正常的方向)
}
- (void)loadView{
    [super loadView];
}
- (instancetype)initWithUserId:(NSString *)userId
{
    self = [super init];
    if (self) {
        self.userId = userId;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:248/255.0 green:248/255.0 blue:248/255.0 alpha:1.0];
    
    ///布局界面
    [self setupUI];
    
    ///初始化聊天数据
    [self.dataSource proLoadMessages:^{
        ///聊天列表滚到底部
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            [self scrollToBottom:NO];
        }];
        
    }];
    
    

    
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self addNoticefication];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self removeNoticefication];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)dealloc{
    NSLog(@"NCChatViewController已释放");
}
#pragma mark- 公开的方法
- (void)setupUI{
    [self.view addSubview:self.chatTableView];
    [self.view addSubview:self.chatInputView];
    
    [self.chatTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        
    }];
    [self.chatInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.chatTableView.mas_bottom);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(self.view);
        }
    }];
    __weak typeof(self) weakSelf = self;
    self.chatTableView.mj_header = [NCRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf.chatTableView.mj_header setState:MJRefreshStateIdle];
        @try{
            ///原有数据条数
            NSUInteger oldCount = weakSelf.dataSource.messages.count;
            [weakSelf.dataSource loadMoreMessages:^(NSUInteger count){
                NSIndexPath *indexPath;
                NSLog(@"更多历史消息:%ld",count);
                if (oldCount == 0) {
                    ///原有数据为零时
                    
                    ///新返回的数据如果是0,返回不执行以下操作
                    if (count == 0) {
                        return ;
                    }
                    indexPath = [NSIndexPath indexPathForRow:count-1 inSection:0];
                }
                else{
                    ///原有数据不为零时
                    indexPath = [NSIndexPath indexPathForRow:count inSection:0];
                }
                ///加载更多数据完毕
                [[NSOperationQueue mainQueue]addOperationWithBlock:^{
                    [weakSelf.chatTableView reloadData];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //刷新完成
                        [weakSelf.chatTableView selectRowAtIndexPath:indexPath  animated:NO scrollPosition:UITableViewScrollPositionTop];
                    });
                    
                }]; 
            }];
        }
        @catch (NSException *exception) {
            NSLog(@"%@",[exception description]);
        }
        @finally
        {
            
        }
        
    }];
    
}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
}
- (void)addNoticefication{
    //监听近距离事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sensorStateChange:)name:UIDeviceProximityStateDidChangeNotification object:nil];
    //监听当键盘将要出现时
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //监听当键将要退出时
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    //选择表情通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveEmojiInfo:) name:WBEmotionDisplayBoardDidSelectEmojiNotifi object:nil];
    //表情键盘发送通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveKeyBoardSendClick:) name:WBEmotionDisplayBoardSendClickNotifi object:nil];
    //语音完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioCompleteFinishNotification:) name:WBAudioCompleteFinishNotification object:nil];
    //消息发送失败通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(messageSendFailNotification:) name:NCChatMessageSendFailNotifi object:nil];
    //点击消息图片通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(messagePhotoTapNotification:) name:NCChatMessagePhotoTapNotifi object:nil];
    
}
- (void)removeNoticefication{
    //销毁的时候停止语音播放
    [WBTLAudioPlayer.sharedAudioPlayer.player stop];
    //监听近距离事件
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIDeviceProximityStateDidChangeNotification object:nil];
    //监听当键盘将要出现时
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    //监听当键将要退出时
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    //选择表情通知
    [[NSNotificationCenter defaultCenter]removeObserver:self name:WBEmotionDisplayBoardDidSelectEmojiNotifi object:nil];
    //表情键盘发送通知
    [[NSNotificationCenter defaultCenter]removeObserver:self name:WBEmotionDisplayBoardSendClickNotifi object:nil];
    //语音完成通知
    [[NSNotificationCenter defaultCenter]removeObserver:self name:WBAudioCompleteFinishNotification object:nil];
    //消息发送失败通知
    [[NSNotificationCenter defaultCenter]removeObserver:self name:NCChatMessageSendFailNotifi object:nil];
    //图片消息点击通知
    [[NSNotificationCenter defaultCenter]removeObserver:self name:NCChatMessagePhotoTapNotifi object:nil];
}
#pragma mark -  Notification Callback
- (void)receiveEmojiInfo:(NSNotification *)notification{
    NSString *text = notification.userInfo[@"text"];
    // delete
    if ([text isEqualToString:@"-1"]) {
        [self.chatInputView.inputView deleteBackward];
    }else{
        [self.chatInputView.inputView insertText:text];
    }
}
- (void)receiveKeyBoardSendClick:(NSNotification *)notification{
    NSLog(@"当你看到这条信息的时候,说明你要实现自己的receiveKeyBoardSendClick:notification方法了");
    //默认实现如下
    NCChatTextMessage *message = [NCChatTextMessage messageWith:self.chatInputView.inputView.text senderId:self.userId date:[NSDate date]];
    [self.dataSource addMessages:message complete:^{
        [self finishSend];
    }];
}

- (void)messageSendFailNotification:(NSNotification *)notification{
    NSLog(@"当你看到这条信息的时候,说明你要实现自己的messageSendFailNotification:notification方法了");
    //默认实现如下
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *del = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        ///要删除的消息
        NCChatAudioMessage *message = (NCChatAudioMessage*)notification.object;
        NSUInteger index = [self.dataSource.messages indexOfObject:message];
        ///删除消息
        [self.dataSource delectMessage:notification.object complete:^{
            [CATransaction begin];
            [self.chatTableView beginUpdates];

            [CATransaction setCompletionBlock: ^{
                [self scrollToBottom:YES];
                NSLog(@"动画结束");
            }];
            [self.chatTableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
            [self.chatTableView endUpdates];
            [CATransaction commit];
    
            
        }];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:del];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}
- (void)messagePhotoTapNotification:(NSNotification *)notification{
    NSLog(@"当你看到这条信息的时候,说明你要实现自己的messagePhotoTapNotification:notification方法了");
}
- (void)audioCompleteFinishNotification:(NSNotification *)notification{
    NSLog(@"当你看到这条信息的时候,说明你要实现自己的audioCompleteFinishNotification:notification方法了");
    //默认实现如下
    NSString *duration = notification.userInfo[@"duration"];
    NSString *path = notification.userInfo[@"path"];
    
    NCChatAudioMessage *message = [NCChatAudioMessage messageWith:path time:[duration integerValue] senderId:self.userId date:[NSDate date]];
    [self.dataSource addMessages:message complete:^{
        [self finishSend];
        
    }];
}
-(void)sensorStateChange:(NSNotificationCenter *)notification;
{
    //如果此时手机靠近面部放在耳朵旁，那么声音将通过听筒输出，并将屏幕变暗（省电啊）
    if ([[UIDevice currentDevice] proximityState] == YES)//黑屏
    {
        NSLog(@"进入听筒模式");
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
        
    }
    else//没黑屏幕
    {
        
        NSLog(@"进入免提模式");
        if (WBTLAudioPlayer.sharedAudioPlayer.isPlaying) {
            ///如果在播放语音,提示
            [NCChatAudioTipsView show:@"已从听筒切换回扬声器播放" inView:self.view];
            
        }
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
        
        
    }
}
//当键盘出现
- (void)keyboardWillShow:(NSNotification *)notification
{
    
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    int height = keyboardRect.size.height;
    NSLog(@"显示键盘:%@",NSStringFromCGRect(keyboardRect));
    [self.chatInputView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.chatTableView.mas_bottom);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).mas_offset(-height+self.view.safeAreaInsets.bottom);
        } else {
            make.bottom.equalTo(self.view).mas_offset(-height);
        }
        
    }];
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
    [self scrollToBottom:YES];
    
}

//当键退出
- (void)keyboardWillHide:(NSNotification *)notification
{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    int height = keyboardRect.size.height;
    NSLog(@"隐藏键盘:%@",NSStringFromCGRect(keyboardRect));
    [self.chatInputView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.chatTableView.mas_bottom);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(self.view);
        }
    }];
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
    [self scrollToBottom:NO];
    
}
- (void)finishSend{
    if (self.dataSource.messages.count == 0) {
        return;
    }
    @try{
        NSIndexPath *lastCell = [NSIndexPath indexPathForRow:self.dataSource.messages.count-1 inSection:0];
        [self.chatTableView insertRowsAtIndexPaths:@[lastCell] withRowAnimation:UITableViewRowAnimationBottom];
        [self.chatTableView selectRowAtIndexPath:lastCell animated:YES scrollPosition:UITableViewScrollPositionTop];
    }
    @catch (NSException *exception) {
        NSLog(@"%@",[exception description]);
    }
    @finally
    {
        
    }

    

    
    
    
 
}
- (void)scrollToBottom:(BOOL)animated{
    if (self.dataSource.messages.count == 0) {
        return;
    }
    @try
    {
        ///不使用固有动画
        if (animated) {
            [UIView animateWithDuration:0.5 animations:^{
                
                [self.chatTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataSource.messages.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
            }];
        }
        else{
            
            [self.chatTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataSource.messages.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
        }
        
    
    }
    @catch (NSException *exception) {
        NSLog(@"%@",[exception description]);
    }
    @finally
    {
        
    }

    
    

    
    
}
#pragma mark -  UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    UIPanGestureRecognizer *pan = scrollView.panGestureRecognizer;
    CGFloat voleticy = [pan velocityInView:scrollView].y;
    if (voleticy <= 10)
    {
        //当往下拉的幅度超过10像素的时候才继续处理
        return;
    }
    //如果不处于语音状态,都变成正常收起键盘的状态
    if (self.chatInputView.status != NCChatInputStatusAudio) {

        self.chatInputView.status = NCChatInputStatusNomal;
    }
    
    if ([[UIMenuController sharedMenuController] isMenuVisible]) {
        [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
    }
}
#pragma mark- UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section NS_AVAILABLE_IOS(7_0){
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForFooterInSection:(NSInteger)section NS_AVAILABLE_IOS(7_0){
    return 0;
}
/*
 图片消息的显示是被控制在一定范围内的(cell中已做了样式控制)、语音、撤回消息的显示样式是固定的，这些类的消息高度直接预估一个固定值就够用了
 文本消息、群通知消息的高度主要依赖于文本内容的多少，要想效果好，还是要计算一下文本主体高度的（虽然还是有高度的计算工作，但在auto sizing机制下，仅需计算出对高度影响最大的文本的高度即可）
 */
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NCChatMessage *msg = self.dataSource.messages[indexPath.row];
    if ([msg isMemberOfClass:[NCChatTextMessage class]]) {
        return 50;
        
    }
    else if ([msg isMemberOfClass:[NCChatPhotoMessage class]]) {
        return 180;
        
    }
    else if ([msg isMemberOfClass:[NCChatAudioMessage class]]) {
        return 50;
        
    }
    else if ([msg isMemberOfClass:[NCChatCustomMessage class]]) {
        return 150;
        
    }
    else if ([msg isMemberOfClass:[NCChatSystemMessage class]]) {
        return 80;
        
    }
    
    return 80;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.messages.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NCChatMessage *msg = self.dataSource.messages[indexPath.row];
    msg.showTime = ((indexPath.row % 3) == 0);
    ///系统消息
    if ([msg isMemberOfClass:[NCChatSystemMessage class]]) {
        NCChatViewSystemCell  *cell = (NCChatViewSystemCell*)[tableView dequeueReusableCellWithIdentifier:systemCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.message = msg;
        return cell;
        
    }
    ///自定义消息(小蜜消息)
    else if ([msg isMemberOfClass:[NCChatCustomMessage class]]) {
        NCChatViewCustomCell  *cell = (NCChatViewCustomCell*)[tableView dequeueReusableCellWithIdentifier:customCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.message = msg;
        return cell;
    }
    ///文本消息
    else if ([msg isMemberOfClass:[NCChatTextMessage class]]) {
        if ([msg.senderId isEqualToString:self.userId]) {
            NCChatViewRightCell *cell = (NCChatViewRightCell*)[tableView dequeueReusableCellWithIdentifier:rightCellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.message = msg;
            return cell;
        }
        else{
            NCChatViewLeftCell *cell = (NCChatViewLeftCell*)[tableView dequeueReusableCellWithIdentifier:leftCellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.message = msg;
            return cell;
        }

    }
    ///图片消息
    else if ([msg isMemberOfClass:[NCChatPhotoMessage class]]) {
        if ([msg.senderId isEqualToString:self.userId]) {
            NCChatViewRightPhotoCell *cell = (NCChatViewRightPhotoCell*)[tableView dequeueReusableCellWithIdentifier:rightPhotoCellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.message = msg;
            return cell;
        }
        else{
            NCChatViewLeftPhotoCell *cell = (NCChatViewLeftPhotoCell*)[tableView dequeueReusableCellWithIdentifier:leftPhotoCellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.message = msg;
            return cell;
        }
    }
    ///语音消息
    else if ([msg isMemberOfClass:[NCChatAudioMessage class]]) {
        if ([msg.senderId isEqualToString:self.userId]) {
            NCChatViewRightAudioCell *cell = (NCChatViewRightAudioCell*)[tableView dequeueReusableCellWithIdentifier:rightAudioCellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.message = msg;
            return cell;
        }
        else{
            NCChatViewLeftAudioCell *cell = (NCChatViewLeftAudioCell*)[tableView dequeueReusableCellWithIdentifier:leftAudioCellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.message = msg;
            return cell;
        }
    }
    ///如果是自定义消息,或者别的消息,请自己在子类中实现以下的代码,在cell == nil的时候返回子类自己定义的消息视图,记得自定义消息务必要继承自NCChatMessage
//    UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
//    if (cell == nil) {
//
//    }
    return nil;
}

#pragma mark- NCChatInputViewDataSource
- (NSArray<NSString *> *)chatInputViewMoreActionTitles{
    return @[@"照片",@"拍照"];
}
- (NSArray<UIImage *> *)chatInputViewMoreActionImages{
    return @[NCChatUIImage(@"photo"),NCChatUIImage(@"camera")];
}
#pragma mark- NCChatInputViewDelegate
- (void)chatInputViewMoreActionWithIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"点击了:%ld",indexPath.row);
    switch (indexPath.row) {
        case 0:
        {
            [self selectPictureWithType:UIImagePickerControllerSourceTypePhotoLibrary];
        }
            break;
        case 1:
        {
            [self selectPictureWithType:UIImagePickerControllerSourceTypeCamera];
        }
            break;
            
        default:
            break;
    }
}
///文本发送
- (void)chatInputViewSendText:(NSString *)text{
    ///默认实现如下
    [self.dataSource addMessages:[NCChatTextMessage messageWith:text senderId:self.userId date:[NSDate date]] complete:^{
        [self finishSend];
    }];
}
#pragma mark- UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSLog(@"当你看到这条信息的时候,说明你要实现自己的imagePickerController:picker:didFinishPickingMediaWithInfo方法了");
    //默认实现如下
    UIImage *image = (UIImage*)info[@"UIImagePickerControllerOriginalImage"];
    [picker dismissViewControllerAnimated:YES completion:^{
        CGSize size = [UIImage imageSizeWithImage:image];
        ///发送图片信息
        NCChatPhotoMessage *rightMessage = [NCChatPhotoMessage messageWith:image previewSize:size senderId:self.userId date:[NSDate date]];
        [self.dataSource addMessages:rightMessage complete:^{
            [self finishSend];
        }];

    }];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    //默认实现如下
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}
@end
